package com.sz.listener;

import com.sz.bean.Sysini;
import com.sz.bean.SysiniConfig;
import com.sz.pojo.frame.BaseObject;
import com.sz.util.ToolStr;
import org.apache.log4j.Logger;

import javax.persistence.Transient;
import javax.servlet.ServletContext;
import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;
import javax.servlet.http.HttpSessionEvent;
import javax.servlet.http.HttpSessionListener;
import java.lang.reflect.Method;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.TimeZone;

/**
 * @框架文件
 * @author   sz
 *
 */
public class AppStartListener implements ServletContextListener, HttpSessionListener {

    private Logger logger = Logger.getLogger(AppStartListener.class);
    private ServletContext application;
    private Sysini sysini;
    public void contextInitialized(ServletContextEvent sce) {
        logger.info("应用程序初始化开始……");
        TimeZone tz = TimeZone.getTimeZone("GMT+8");
        TimeZone.setDefault(tz);

        application = sce.getServletContext();
        sysini = SysiniConfig.getSysini();
        sysini(sysini);
        application.setAttribute("ctx", sysini.getUrl() + sysini.getAppName());
        logger.debug("应用程序初始化完成。");
    }

    public void contextDestroyed(ServletContextEvent sce) {
        logger.info("应用程序注销……");
    }

    public void sessionCreated(HttpSessionEvent arg0) {
        logger.info("Session创建");
        arg0.getSession().setAttribute("appName", sysini.getAppName());
    }

    public void sessionDestroyed(HttpSessionEvent arg0) {
        logger.info("Session销毁");
    }

    /**
     * 根据类，取所有参数的值
     */
    @Transient
    public Sysini sysini(Sysini model) {
        Class<? extends Object> clazz = model.getClass();
        for (Method method : clazz.getMethods()) {
            if (method.getName().indexOf("set") == 0) {
                String temp = method.getName().substring(3);
                String property = ToolStr.indexCodeLowerCase(temp);
                Method getMothod = null;
                Object object = null;
                try {
                    getMothod = clazz.getMethod("get" + temp);
                    object = getMothod.invoke(model);
                } catch (NoSuchMethodException e) {
                    try {
                        getMothod = clazz.getMethod("is" + temp);
                        object = getMothod.invoke(model);
                    } catch (Exception e1) {
                    }
                } catch (Exception e) {
                }
                if (object != null) {
                    if (!(object instanceof Map || object instanceof List || object instanceof Set
                            || object instanceof BaseObject)) {
                        application.setAttribute(property, object);
                    }
                }
            }
        }
        return model;
    }

}
